package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.util.BaseContext;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        long id = Thread.currentThread().getId();
        //1.判断哪些资源需要放行
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login"
        };
        //用户访问的资源路径`
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        //路径匹配器
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            //如果用户访问的资源匹配上,就放行
            if (antPathMatcher.match(url, requestURI)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        //2.判断用户是否登录
        //从session域中获得用户id
        Long employeeID = (Long) request.getSession().getAttribute("employee");
        //2.1  id不为空 用户登录,放行
        if (employeeID != null) {
            //在线程载体中存储用户的id
            BaseContext.set(employeeID);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            //在线程载体中存储用户的id
            BaseContext.set(userId);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
